package com.weaver.qfengx.db;

import com.google.common.collect.Maps;
import org.apache.commons.compress.utils.Lists;
import weaver.conn.mybatis.MyBatisFactory;

import java.sql.*;
import java.util.List;
import java.util.Map;

/**
 * 数据库操作工具类
 * 内部工具类使用，业务系统选择使用DaoUtils
 */
public class DBUtils {

    public static Connection getConn() {
        return MyBatisFactory.sqlSessionFactory.openSession().getConnection();
    }

    public static List<Map<String, Object>> query(String sql, Object... params) throws SQLException {
        Connection connection = getConn();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        putParam(preparedStatement, params);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<Map<String, Object>> res = resultToMapList(resultSet);
        connection.close();
        connection = null; // 显示的标记
        return res;
    }

    private static void putParam(PreparedStatement preparedStatement, Object[] params) throws SQLException {
        for (int i = 1; i <= params.length; i++) {
            preparedStatement.setObject(i, params[i]);
        }
    }

    private static List<Map<String, Object>> resultToMapList(ResultSet resultSet) throws SQLException {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            Map<String, Object> map = Maps.newHashMap();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String name = metaData.getColumnName(i);
                map.put(name, resultSet.getString(name));
            }
            mapList.add(map);
        }
        return mapList;
    }

}
